﻿using Grow.Scheduler.Job;
using Hangfire;

namespace Grow.Scheduler.Hangfire
{
    public class Scheduler : IScheduler
    {
        //public IEnumerable<JobDto> GetJobs()
        //{
        //    return JobStorage.Current.GetConnection().GetRecurringJobs().Select(a => new JobDto(a.Id, a.Cron)).ToList();
        //}

        public void RemoveJob(string jobId)
        {
            RecurringJob.RemoveIfExists(jobId);
        }

        public void TriggerJob(string jobId)
        {
            _ = RecurringJob.TriggerJob(jobId);
        }

        public void AddJob<TJob>(string jobId, string cron, CancellationToken cancellationToken = default)
            where TJob : class, IJob
        {
            RecurringJob.AddOrUpdate<TJob>(jobId, a => a.ExecuteAsync(cancellationToken), cron);
        }

        public void AddJob<TJob, TJobData>(string jobId, TJobData jobData, string cron, CancellationToken cancellationToken = default)
          where TJob : class, IJob<TJobData>
        {
            RecurringJob.AddOrUpdate<TJob>(jobId, a => a.ExecuteAsync(jobData, cancellationToken), cron);
        }


        public void AddSchedule<TJob>(DateTimeOffset enqueueAt, CancellationToken cancellationToken = default)
             where TJob : class, IJob
        {
            _ = BackgroundJob.Schedule<TJob>(a => a.ExecuteAsync(cancellationToken), enqueueAt);
        }


        public void AddSchedule<TJob, TJobData>(TJobData jobData, DateTimeOffset enqueueAt, CancellationToken cancellationToken = default)
            where TJob : class, IJob<TJobData>
        {
            _ = BackgroundJob.Schedule<TJob>(a => a.ExecuteAsync(jobData, cancellationToken), enqueueAt);
        }
    }
}
